package com.hua.api.core.framework.util.crypto;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;

public class AESKit {

    public static final String IV = "F4vfSfhx3nPaLSeP";
    public static final String KEY = "PwaWQ5rEFEl3u9yR";


    public static String sha1(String str){
        if (str == null || str.length() == 0) {
            return null;
        }
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };

        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("GBK"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }

    public static String encrypt(String sSrc) {
        try {
            return  encrypt(sSrc, KEY.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



    /*******************************************************************
     * AES加密算法
     * @author moyun
     * 加密用的Key 可以用26个字母和数字组成，最好不要用保留字符，虽然不会错，至于怎么裁决，个人看情况而定    此处使用AES-128-CBC加密模式，key需要为16位。
     * */

    //加密
    private static String encrypt(String sSrc, byte[] raw) throws Exception {

//        if (sKey == null) {
//            System.out.print("Key为空null");
//            return null;
//        }
//        // 判断Key是否为16位
//        if (sKey.length() != 16) {
//            System.out.print("Key长度不是16位");
//            return null;
//        }
//        byte[] raw = sKey.getBytes();

        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"   
        IvParameterSpec iv = new IvParameterSpec(IV.getBytes());//使用CBC模式，需要一个向量iv，可增加加密算法的强度   
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes());

        return Base64.encodeBase64String(encrypted);//此处使用BAES64做转码功能，同时能起到2次
    }

    public static String decrypt(String sSrc) {
        try {
            return decrypt(sSrc, KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //解密
    private static String decrypt(String sSrc, String sKey) throws Exception {

        // 判断Key是否正确   
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        // 判断Key是否为16位   
        if (sKey.length() != 16) {
            System.out.print("Key长度不是16位");
            return null;
        }
        byte[] raw = sKey.getBytes("ASCII");

        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] encrypted1 = Base64.decodeBase64(sSrc);//先用bAES64解密  
        try {
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception e) {
            //logger.info(e.toString());
            return null;
        }
    }

//    public static void main(String[] args) throws Exception {
//
//        String iv = "UPxyIn1SB3PsEtsbKaE7xQ==";
//        String ivs= "wQilJaDQ7vzBNIkWkI9kYQ==";
//        String str ="T5P1M3kI+YTONqHBKOsWlXdXJ/bdKfXIpu5TKv/UHxfYrceMDotMCXAc9FbT9/W51Ms+ldEoJQjwFPaj03u9v4OCNyPjn1UQRjEDiLc/LLJ43QKBqZ4sXoxbgtD4wVK7nP2c58CYqqhGH8O36YZqgKQgiLSeZKNS8BtTz74YfckuGDhAsonT70WfdjHDy5Epsk+wdSRNBeH7sFBN1jNzPdIMiRLb2mz+mjpF+VFQZEM2AY0kCUXrs3/lmyO1kTEhrHpMO8cfFVKeOii/YVaKaBscMpM21GbDPP7Zh87FEszC0+fI6uLwBS0a5Q2zTiUHewTfcZhsTuh33alUYJzVOQanR0QST3yUGG2CdQQMB8KACM6b0PBgXXhx8HYGJsfMRf2jxIXVu1Gz4szElkbLTHl4mye6uUh85Msw2xHuDnHwuQOstFU9OR35C7vo0bVOcmaruNsuC3w0P2QG7BfocLBe1/teJtbO374nIL4oVdM=";
//        //String encrypedData = "JaVPm23+3DHJxv8HnXVzDDOpMv6F6Bg0Eg6VEidniJ2gGgijpmenZ6FaC5sERVw134Rc+GP9j7O5GkiweFC2OnC5ggqZ5eRo2WCQfDiQmiCYJmU3mLePPlWz/tRyG+BgtR10Llwixy7Eb/YVGh7v+W4ce26/YNN0JKIz2afDqnFXZLy+jptW2dyoh7lnxgrQuIbibYpGn6e/Mp7kTnGk8X21NkhKRliEQy+Y5UraY/Q7XxaHdy98hA+GKI0NIkkhaO9WgJTPeTmBhTmxzJVgv3D/gpKxNyO6CzVUgByyGmvXd0xVBlz8TJCwy9Xpe/8kqmX7XPkxtABPFm7co46wLM6lpIyqG/ZmO8xAJDjL2Anu8w0HVEorfDyw9NRzK0/F06wK5r1jYsFTRrKnN8vCzcDSu6tbN/3Y1dSSY1OvCAuaXnKJIFTrL3zhYmbo5KyLZdJZKVAII+sQBaIbAaDiUrr7nmPfrUdhwpUqrJv/rfY=";
//        Base64.decodeBase64(iv);
//        byte[] ivKey = Base64.decodeBase64(ivs);
//        String desc = encrypt(str,ivKey);
//        //String str = AESKit.sha1(encrypedData);
//
//        System.out.println(desc);
//
//    }
}
